<template>
  <div class="login">
    <div class="logincontainer">
      <legend>学员管理系统</legend>
      <el-form
        :model="loginForm"
        status-icon
        :rules="logins"
        ref="loginForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha" class="captcha">
          <el-input
            type="text"
            v-model="loginForm.captcha"
            autocomplete="off"
          ></el-input>
          <span class="captcha-svg" v-html="captchaSvg" @click="changeSvg"></span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >登陆</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <p class="bg"></p>
    <video autoplay="autoplay" loop="loop" preload="auto" muted="muted">
      <source
        src="../../../public/video/bg_video.d2d602a9.mp4"
        type="video/mp4"
      />
    </video>
  </div>
</template>
<script>
/*
        @param {rule} 一个表单验证对象
        @param {value} 表单输入框的值
        @param {callback} 一个回调函数，不通过时传参，通过时不传参
    */

//通过解构的方法将api里的Login引入
import { Login } from "../../api/index";
//引入mutation的辅助函数
import { mapMutations } from "vuex";
//引入actions的辅助函数
import { mapActions } from "vuex";
//引入验证码的请求
import {getCaptcha,refreshCaptcha,verifyCaptcha} from "../../api/index"
export default {
  data() {
    var validateUsername = (rule, value, callback) => {
      var uPattern = /^[a-zA-Z0-9_-]{3,16}$/;
      if (uPattern.test(value)) {
        callback();
      } else {
        callback("用户名为4到16位（字母，数字，下划线，减号）");
      }
    };
    var validatePassword = (rule, value, callback) => {
      if (value) {
        callback();
      } else {
        callback("请输入密码");
      }
    };
    var validateCaptcha = (rule, value, callback) => {
      if (value === "" || value.length<5) {
        callback("请输入验证码");
      } else {
        callback();
      }
    }
    return {
      captchaSvg:"",//存储从服务器获取的二维码
      loginForm: {
        username: "",
        password: "",
        captcha:""
      },
      logins: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }]
      }
    };
  },
  methods: {
    //映射mutation
    ...mapMutations(["SET_USERINFO"]),
    //映射actions
    ...mapActions(["FETCH_MENULIST"]),

    //获取验证码
    getCaptchaSvg(){
      getCaptcha()
      .then(res=>{
        console.log(res.data)
        this.captchaSvg=res.data.img
      })
    },
    //点击刷新验证码
    changeSvg(){
      this.getCaptchaSvg()
    },
    submitForm(loginForm) {
      //点击登陆时，调用加载动画
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });

      this.$refs[loginForm].validate(async(valid) => {
        if (valid) {
          //先校验验证码，通过后再执行账号密码的验证
          let verifyRes=await verifyCaptcha(this.loginForm.captcha)
          console.log(verifyRes)
          if(!verifyRes.data.state){
            //如果验证码不正确
            this.$message.error("验证码不正确，请重试")
            setTimeout(() => {
              loading.close();
            }, 0);
            return
          }
          let { username, password } = this.loginForm;
          Login(username, password)
            .then(res => {
              //服务器响应了，关闭加载动画
              setTimeout(() => {
                loading.close();
              }, 0);

              if (res.data.state) {
                //用户名和密码正确
                //将返回的token存在本地
                localStorage.setItem("stu-login-token", res.data.token);
                //将返回的按钮权限存在本地,同时触发vuex,更新state
                localStorage.setItem("stu-permission-buttons",JSON.stringify(res.data.permission.buttons))
                this.$store.dispatch("FETCH_PERMISSION")
                //同时跳转到主页面，然后直接跳到welcom页面
                this.$router.push({ path: "/Welcome" });
                //创建一个localstorage存储用户其他信息
                localStorage.setItem(
                  "stu-userinfo",
                  JSON.stringify(res.data.userInfo)
                );
                //向mutation发送userinfo
                this.SET_USERINFO(res.data.userInfo);
                this.$message({ message: "登陆成功", type: "success" });
                //向actions发送
                this.$store.dispatch("FETCH_MENULIST");
              } else {
                //用户名或密码不正确
                this.$message.error("用户名密码错误");
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else{
          this.$message.error("请输入完整");
          //关闭加载动画
          setTimeout(() => {
            loading.close();
          }, 0);
          return false;
        }
      });
    }
  },
  mounted () {
    this.getCaptchaSvg()
  }
};
</script>
<style>
/* input输入框的样式必须写在不带scoped的style标签里 */
/* 仔细看清楚组件的真实类名和标签名 */
.login .el-form .el-input .el-input__inner {
  color: #fff;
  background: none;
}
.login .el-form label {
  color: #fff;
}
</style>
<style scoped>
.login {
  width: 100%;
  height: 100%;
  position: relative;
}
.login .bg {
  width: 50%;
  height: 100%;
  position: absolute;
  background: url("../../../public/imgs/bg2.fc58c850.png") no-repeat;
  background-size: 50%;
  background-position: 60% 65%;
  opacity: 0.7;
}
.login .logincontainer {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 400px;
  height: 487px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 11px;
  position: absolute;
  top: 15%;
  left: 60%;
}
.login .logincontainer legend {
  color: #fff;
  height: 42px;
  line-height: 42px;
  font-size: 36px;
  margin-bottom: 65px;
  text-align: center;
}
.login .el-form {
  width: 400px;
}
.login .el-form .el-input {
  width: 83%;
}
.login .el-form .el-button {
  width: 83%;
  background: linear-gradient(90deg, #1596fb, #002dff);
}
.login video {
  position: fixed;
  width: 1920px;
  height: 1080px;
  z-index: -1;
}
.captcha .el-input{
  width: 40%!important;
  float: left!important;
}
.captcha .captcha-svg{
  margin-left: 15px;
  cursor:pointer;
}
</style>
